package com.hjy.web;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


@Controller
public class TestController {

    @RequestMapping("/test1")
    public void test1(HttpServletResponse response) throws IOException {
        // 1. 定义一个内存输出流S
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        // 2. 获取 ZipOutputStream
        ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
        // 3. 写入数据
        // 写入该文件在压缩包中的位置
        storeIntoZip(zipOutputStream, "test/text.pdf", "C:\\Users\\hjy\\Desktop\\12-FreeMarker.pdf");
        // 4. 获取zip文件的比特流
        // 必须将其先关上, 或者调用 finish方法, 才能将所有数据写入到 byteArrayOutputStream , 不然流数据不完整
        zipOutputStream.close();
        byte[] bytes = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.close();


        // 6. 设置响应头
        response.reset(); // 清除缓冲区中存在的所有数据以及状态代码和标题
        response.setHeader("Content-Disposition", "attachment; filename=\"miemie.zip\"");
        response.addHeader("Content-Length", "" + bytes.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        // 5. 返回前端
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);


    }

    /**
     * 将一个文件存入zip包中
     *
     * @param zipOutputStream
     * @param nameInZip
     * @param fileLocation
     * @return
     * @throws IOException
     */
    private void storeIntoZip(ZipOutputStream zipOutputStream, String nameInZip, String fileLocation) throws IOException {
        zipOutputStream.putNextEntry(new ZipEntry(nameInZip));
        FileInputStream fileInputStream = new FileInputStream(fileLocation);
        byte[] b = new byte[1024];
        int len;
        while ((len = fileInputStream.read(b, 0, b.length)) != -1) {
            zipOutputStream.write(b, 0, len);
        }

        // 关闭该文件的打包, 等待下一个文件的打包
        zipOutputStream.closeEntry();
        fileInputStream.close();
    }
}

